import { Config } from 'config.js';

class Token {
  constructor() {
    this.verifyUrl = Config.baseUrl + 'token/verify';
    this.tokenUrl = Config.baseUrl + 'token/user';
  }

  /**
   * 校验Token
   */
  verify() {
    // 在缓存获取Token
    var token = wx.getStorageSync('token');

    if (token){
      // 校验是否过期
      this._verifyFromServer(token);
    }else{
      // 重新去服务器获取Token
      this.getTokenFromServer();
    }
  }

  _verifyFromServer(token) {
    var that = this;
    wx.request({
        url: that.verifyUrl,
        method: 'POST',
        data: {
            token: token
        },
        success: function (res) {
            var valid = res.data.isValid;
            if(!valid){
                that.getTokenFromServer();
            }
        }
    })
  }

  getTokenFromServer(callBack) {
    var that  = this;
    wx.login({
        success: function (res) {
            wx.request({
                url: that.tokenUrl,
                method:'POST',
                data:{
                    code:res.code
                },
                success:function(result){
                    wx.setStorageSync('token', result.data.data.token);
                    callBack&&callBack(result.data.data.token);
                },
                fail:function(err){
                  console.log(err);
                }
            })
        }
    })
}
}

export {Token};